package gui;

import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import model.Location;
import service.Service;

/**
 * 
 * @author Ceslovas Lopan
 * 
 */
public class EditLocation extends JFrame {
	private final Controller controller = new Controller();
	private JButton btnEdit, btnCancel;
	private JCheckBox chckbxActive;
	private StackPanel owner;
	private JPanel panel1;
	private JLabel lblToChangeThis;

	public EditLocation(StackPanel owner) {
		this.owner = owner;

		this.setSize(300, 120);

		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

		setTitle("Edit Location");
		getContentPane().setLayout(new GridLayout(3, 0, 0, 0));

		panel1 = new JPanel();
		FlowLayout flowLayout1 = (FlowLayout) panel1.getLayout();
		flowLayout1.setAlignment(FlowLayout.LEFT);
		getContentPane().add(panel1);

		lblToChangeThis = new JLabel("To change this, location should be empty");
		panel1.add(lblToChangeThis);
		lblToChangeThis.setVisible(false);

		JPanel panel = new JPanel();
		FlowLayout flowLayout = (FlowLayout) panel.getLayout();
		flowLayout.setAlignment(FlowLayout.LEFT);
		getContentPane().add(panel);

		chckbxActive = new JCheckBox("Location is active");
		panel.add(chckbxActive);
		chckbxActive.setSelected(owner.getStackLocation().isActive());

		JPanel panel2 = new JPanel();
		FlowLayout flowLayout2 = (FlowLayout) panel2.getLayout();
		flowLayout2.setVgap(2);
		flowLayout2.setAlignment(FlowLayout.RIGHT);
		getContentPane().add(panel2);

		btnEdit = new JButton("Edit");
		panel2.add(btnEdit);
		btnEdit.addActionListener(controller);

		btnCancel = new JButton("Cancel");
		panel2.add(btnCancel);
		btnCancel.addActionListener(controller);

		if (owner.getStackLocation().getStack() != null) {
			chckbxActive.setEnabled(false);
			lblToChangeThis.setVisible(true);
			btnEdit.setEnabled(false);
		}

	}

	private class Controller implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent e) {
			if (e.getSource() == btnCancel) {
				EditLocation.this.dispose();
			} else if (e.getSource() == btnEdit) {
				Location l = Service.getInstance().editLocation(
						owner.getStackLocation(), chckbxActive.isSelected());

				if (l != null) {
					owner.updateView();
					EditLocation.this.dispose();
				} else {
					JOptionPane.showMessageDialog(EditLocation.this,
							"Location could not be edited", "Error",
							JOptionPane.ERROR_MESSAGE);
				}
			}

		}

	}
}